<template>
  <div
    style="width: 750px"
    :class="{ hidden: !selfShow }"
    id="bg"
    v-if="myData"
  >
    <div class="main-content">
      <!--基本信息-->
      <div class="container">
        <span class="title">基本信息</span>
        <div class="d1">
          <span>用户名</span>
          <div class="d2">
            <span>{{ messageData.nickName }}</span>
          </div>
        </div>
        <div class="d1">
          <span>账号</span>
          <div class="d2">
            <span>{{ myData.account }}</span>
          </div>
        </div>
        <div class="d1">
          <span>账户余额</span>
          <div class="d2">
            <span style="color: red">￥{{ messageData.userMoney }}</span>
          </div>
        </div>
      </div>
      <div class="container">
        <span class="title">资源费用</span>
        <el-table
          v-loading="loading"
          element-loading-background="rgba(255, 255, 255, 1)"
          :data="myData.resourceDetail"
          border
          style="width: 100%"
        >
          <el-table-column
            prop="resourceName"
            label="资源名称"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="resourceStatus"
            label="资源状态"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.resourceStatus | resourceStatusFilter }}
            </template>
            <!-- 已购买 -->
          </el-table-column>
          <el-table-column prop="resourceType" label="资源类型" align="center">
            <template slot-scope="scope">
              {{ scope.row.resourceType | typeFilter }}
            </template>
          </el-table-column>
          <el-table-column
            prop="resourcePrice"
            width="100"
            label="资源价格"
            align="center"
          >
          </el-table-column>
        </el-table>
      </div>
      <!--总价-->
      <div>
        <hr style="width: 605px; margin-left: 75px" />
        <div class="d1" style="margin-left: 20px; margin-top: 20px">
          <span
            style="
              margin-left: 66px;
              font-weight: bolder;
              margin-top: 20px;
              font-size: 14px;
              color: #1f1f1f;
            "
          ></span>
          <span
            style="
              color: red;
              font-size: 20px;
              font-weight: bolder;
              margin-top: 15px;
              margin-left: -240px;
            "
          ></span>
          <button class="btn4" @click="send">确认订单,去发布</button>
        </div>
        <div style="margin-left: 85px; margin-top: 8px">
          <span style="font-size: 15px; color: #515151"
            >说明：当图书三审通过后自动扣费</span
          >
        </div>
        <div
          style="
            width: 750px;
            height: 1px;
            background: #ffffff;
            margin-bottom: 80px;
            margin-top: 30px;
          "
        ></div>
      </div>
    </div>
    <div id="tips" class="tips" :hidden="tips">
      <img :src="resultIcon" />
      <span>{{ msg }}</span>
    </div>
  </div>
</template>

<script>
import ajax from "../../common/ajax";
import api from "../../common/api";
import encryption from "../../common/encryption";
import order from "../../enum/orders/order";

let context;
let u;

var re = /^[0-9]*[1-9][0-9]*$/;
let myArr = [];
export default {
  filters: {
    resourceStatusFilter(resourceStatus) {
      const Status = {
        0: "已购买",
        1: "未购买",
      };
      return Status[resourceStatus];
    },
    typeFilter(resourceType) {
      const type = {
        0: "模型",
        1: "普通模型",
        5: "自定义模型",
        6: "视频",
        7: "图片",
        8: "网页链接",
        13: "音频",
        21: "网页模型",
        22: "二级节点模型",
      };
      return type[resourceType];
    },
  },
  name: "AddMountSlot",
  data() {
    return {
      selfShow: true,
      bookNum: 2,
      resourceTotalAmount: 0,
      resourceTotal: 0,
      myData: null,
      radio: "1",
      resultIcon: "../assets/images/icon_error.png",
      msg: "",
      tips: true,
      resourceList: null,
      checked1: false,
      checked2: false,
      guidData: null,
      disabled: false,
      priceInfo: null,
      showCommon: false,
      showThird: false,
      showCustom: false,
      showCustomText: false,
      showThirdText: false,
      showCommonText: false,
      messageData: {},
      getMyTotal: 0,
      list: [],
      newlist: [],
      loading: true,
    };
  },
  // computed: {
  //   getMyTotal() {
  //     // this.newArry = this.myData.resourceDetail.map((o) => {
  //     //   return o.resourcePrice;
  //     // });
  //     // var sum = 0;
  //     // for (let i = 0; i < this.newArry.length; i++) {
  //     //   sum = sum + this.newArry[i];
  //     // }
  //     // return sum;
  //   },
  // },

  //去掉横向滚动条
  beforeCreate() {
    document.querySelector("body").setAttribute("style", "overflow-x:hidden");
  },
  beforeDestroy() {
    document.querySelector("body").removeAttribute("style");
  },
  created() {
    //初始化价格
    initResPrice(this);
    u = navigator.userAgent;
    let that = this;
    if (u.indexOf("Trident") > -1) {
      console.log(33);
      let a = window.external.JSCallMFCFunctionJson();
      this.myData = JSON.parse(a);
      ajax.get({
        url:
          api.Info.routeName + api.Info.children.account + this.myData.userId,
        success: function (res) {
          this.messageData = JSON.parse(encryption.decryptionMxr(res));
          console.log("success");
        },
      });
      let models = [];
      let publicModels = [];
      let customizeModels = [];
      this.myData.resourceDetail.forEach((el) => {
        if (el.resourceBelong === 3) {
          models.push(el.resourceId);
        } else if (el.resourceBelong === 4) {
          customizeModels.push(el.resourceId);
        } else {
          publicModels.push(el.resourceId);
        }
      });

      let Jsons = {
        userId: this.myData.userId,
        models: models,
        publicModels: publicModels,
        customizeModels: customizeModels,
      };
      ajax.post({
        url:
          api.resourceDetail.routeName +
          api.resourceDetail.children.detail +
          "?r=" +
          Math.random(),
        data: Jsons,
        success(res) {
          that.resourceList = JSON.parse(encryption.decryptionMxr(res)).detail;
          console.log(JSON.parse(encryption.decryptionMxr(res)).detail);

          for (let i = 0; i < that.resourceList.length; i++) {
            let cc = {};
            cc.resourceName = that.resourceList[i].modelName;
            cc.resourceStatus = that.resourceList[i].authType;
            cc.resourceType = that.resourceList[i].type;
            cc.resourcePrice = that.resourceList[i].priceRange;
            cc.resourceNo = that.resourceList[i].modelNo;
            cc.resourceSource = that.resourceList[i].resourceType;
            cc.resourceUseType = that.resourceList[i].resourceUseType;
            myArr.push(cc);

            //获取虚拟价格
            let total = 0;
            let t = 0;
            if (that.resourceList.length !== 0) {
              that.resourceList.forEach((el) => {
                total += el.authType === 2 ? parseInt(el.priceRange) : 0;
                t += parseInt(el.priceRange);
                if (el.resourceType === 4) {
                  that.showCustomText = true;
                }
                if (el.resourceType === 2) {
                  that.showThirdText = true;
                }
                if (el.resourceType === 1) {
                  that.showCommonText = true;
                }
              });
              that.resourceTotalAmount = total.toFixed(2);
              that.resourceTotal = t.toFixed(2);
            }
          }
          console.log(myArr);
        },
        fail(res) {
          alert(JSON.stringify(res) + "失败");
        },
      });

      //获取复选框以及图书册数
      ajax.get({
        url: api.guid.routeName,
        data: {
          bookGuid: this.myData.bookGuid,
        },
        success(res) {
          that.guidData = res;

          if (that.myData.bookState === 1) {
            that.bookNum = 10;
            // that.bookNum = that.guidData.bookNum.toString();
            // document.getElementById("addInput").setAttribute("readonly", "readonly")

            //获取复选框状态
            that.checked1 = that.guidData.isAuditOneCharged == 0 ? true : false;
            that.checked2 = that.guidData.isAuditTwoCharged == 0 ? true : false;
            that.disabled = true;
          }
        },
      });
    } else if (u.indexOf("AppleWebKit") > -1) {
      //qt交互
      console.log(22);
      new QWebChannel(qt.webChannelTransport, function (channel) {
        console.log("create webChannel succeed.");
        context = channel.objects.Js2QtFunction;
        context.SigSendMessageToJS.connect(function (message) {
          console.log("connect success");
          that.bookNum = 10;
          that.radio = "1";
          that.checked1 = false;
          that.checked2 = false;
          that.disabled = false;
          that.myData = JSON.parse(message);

          ajax.get({
            url:
              api.Info.routeName +
              api.Info.children.account +
              that.myData.userId,
            success: function (res) {
              that.messageData = JSON.parse(encryption.decryptionMxr(res));
              console.log("success");
            },
          });
          ajax.get({
            url: api.resource.privateRouteName + api.resource.children.usr,
            data: {
              userId: that.myData.userId,
              pageSize: 999999,
            },
            success(res) {
              this.response = JSON.parse(encryption.decryptionMxr(res));
              that.myData.resourceDetail.map((item) => {
                this.response.list.map((v) => {
                  if (v.resourceId == item.resourceId) {
                    item.resourceStatus = 1;
                  }
                });
              });
              that.loading = false;
              // that.newlist = that.myData.resourceDetail;
            },
          });

          //获取资源信息
          let models = [];
          let publicModels = [];
          let customizeModels = [];
          that.myData.resourceDetail.forEach((el) => {
            if (el.resourceBelong === 3) {
              models.push(el.resourceId);
            } else if (el.resourceBelong === 4) {
              customizeModels.push(el.resourceId);
            } else {
              publicModels.push(el.resourceId);
            }
          });

          let Jsons = {
            userId: that.myData.userId,
            models: models,
            publicModels: publicModels,
            customizeModels: customizeModels,
          };
          ajax.post({
            url:
              api.resourceDetail.routeName +
              api.resourceDetail.children.detail +
              "?r=" +
              Math.random(),
            data: Jsons,
            success(res) {
              that.resourceList = JSON.parse(
                encryption.decryptionMxr(res)
              ).detail;
              console.log(JSON.parse(encryption.decryptionMxr(res)).detail);

              myArr = [];
              for (let i = 0; i < that.resourceList.length; i++) {
                let cc = {};
                cc.resourceName = that.resourceList[i].modelName;
                cc.resourceStatus = that.resourceList[i].authType;
                cc.resourceType = that.resourceList[i].type;
                cc.resourcePrice = that.resourceList[i].priceRange;
                cc.resourceNo = that.resourceList[i].modelNo;
                cc.resourceSource = that.resourceList[i].resourceType;
                cc.resourceUseType = that.resourceList[i].resourceUseType;
                myArr.push(cc);

                //获取虚拟价格
                let total = 0;
                let t = 0;
                if (that.resourceList.length !== 0) {
                  that.resourceList.forEach((el) => {
                    total += el.authType === 2 ? parseInt(el.priceRange) : 0;
                    t += parseInt(el.priceRange);
                    if (el.resourceType === 4) {
                      that.showCustomText = true;
                    }
                    if (el.resourceType === 2) {
                      that.showThirdText = true;
                    }
                    if (el.resourceType === 1) {
                      that.showCommonText = true;
                    }
                  });
                  that.resourceTotalAmount = total.toFixed(2);
                  that.resourceTotal = t.toFixed(2);
                }
              }
              console.log(myArr);
            },
            fail(res) {
              alert(JSON.stringify(res) + "失败");
            },
          });

          //获取复选框以及图书册数
          ajax.get({
            url: api.guid.routeName,
            data: {
              bookGuid: that.myData.bookGuid,
            },
            success(res) {
              that.guidData = res;

              if (that.myData.bookState === 1) {
                // that.bookNum = that.guidData.bookNum.toString();
                that.bookNum = 10;
                // document.getElementById("addInput").setAttribute("readonly", "readonly")

                //获取复选框状态
                that.checked1 =
                  that.guidData.isAuditOneCharged == 0 ? true : false;
                that.checked2 =
                  that.guidData.isAuditTwoCharged == 0 ? true : false;
                that.disabled = true;
              }
            },
          });
        });
        //给编辑器端发送消息，获取数据
        try {
          context.useFunction_ChannelCreated(true);
        } catch (e) {
          console.log("old version");
        }
      });
    }
  },
  mounted() {
    console.log(this.myData);
  },
  methods: {
    /**
     * 关闭弹窗
     */
    onClose() {
      if (u.indexOf("Trident") > -1) {
        window.external.JSCallMFCFunctionClose();
      } else if (u.indexOf("AppleWebKit") > -1) {
        context.useFunction_Close(false);
      }
    },

    /**
     * 提交订单
     */
    send() {
      // if(u.indexOf('AppleWebKit') > -1){
      //   context.useFunction_Close(true)
      // }
      console.log(this.myData.resourceDetail.length);
      this.resourceId = this.myData.resourceDetail
        .map((item) => item.resourceId)
        .join();
      let that = this;
      let param = {
        userId: this.myData.userId,
        bookGuid: this.myData.bookGuid,
        account: this.myData.account,
        pressId: this.myData.pressId,
        contacts: this.myData.contacts,
        contactWay: this.myData.contactWay,
        projectName: this.myData.projectName,
        bookOrderDetailModelList: myArr,
        resourceLocalDetail: this.myData.resourceLocalDetail,
        resourceMarkerDetail: this.myData.resourceMarkerDetail,
        resourceTTSDetail: this.myData.resourceTTSDetail,
        ebookPageSize: this.myData.ebookPageSize,
        resourceSize: this.myData.resourceSize,
        bookNum: this.bookNum,
        ttsNum: this.myData.ttsNum,
        isProcessBook: parseInt(this.radio),
        ebookPageNum: this.myData.ebookPageNum,
        resourceNum: this.myData.resourceNum,
        resourceTotalAmount: this.resourceTotalAmount,
        storageTotalAmount: 11,
        cdnTotalAmount: 11,
        ttsTotalAmount: 11,
        processBookTotalAmount: 11,
        totalAmount: this.getMyTotal,
        payableAmount: this.getMyTotal,
        isAuditOneCharged: 11,
        isAuditTwoCharged: 112,
        onlineServiceAmount: 11,
        bookAuditTotalAmount: 11,
        resourceIds: this.resourceId,
      };
      if (this.bookNum == "") {
        this.msg = "图书发行数量不为空";
        this.resultIcon = require("../../assets/images/icon_error.png");
        this.tips = false;
        setTimeout(function () {
          that.tips = true;
        }, 1500);
      } else if (!re.test(this.bookNum)) {
        this.msg = "图书发行量只能输入大于0的整数";
        this.resultIcon = require("../../assets/images/icon_error.png");
        this.tips = false;
        setTimeout(function () {
          that.tips = true;
        }, 1500);
      } else {
        ajax.post({
          url:
            api.orders.routeName +
            api.orders.children.book +
            "?t=" +
            new Date().getTime(),
          data: param,
          success(res) {
            that.msg = "提交成功";
            that.resultIcon = require("../../assets/images/ico_success.png");
            that.tips = false;
            setTimeout(function () {
              that.tips = true;
              if (u.indexOf("Trident") > -1) {
                window.external.JSCallMFCFunctionOrderConfirm();
              } else if (u.indexOf("AppleWebKit") > -1) {
                context.useFunction_Close(true);
              }
            }, 1500);
          },
          fail(res) {
            if (res.ErrCode == 100058) {
              that.msg = "资源使用次数不足，需要在资源商店重新购买！";
            } else {
              that.msg = "提交失败";
            }
            that.resultIcon = require("../../assets/images/icon_error.png");
            that.tips = false;
            setTimeout(function () {
              that.tips = true;
            }, 1500);
          },
        });
      }
    },
  },
};

/**
 * 获取用户信息
 */
// function getUserInfo(that) {
//   console.log(that);
//   ajax.get({
//     url: api.Info.routeName + api.Info.children.account + 4018,
//     success: function (res) {
//       that.messageData = JSON.parse(encryption.decryptionMxr(res));
//       console.log("success");
//     },
//     error(e) {
//       console.log(e);
//     },
//   });
// }

/**
 * 初始化价格
 *
 * @param that VUE对象
 */
function initResPrice(that) {
  ajax.get({
    url: api.resourceDetail.routeName + api.resourceDetail.children.price,
    encryption: true,
    success(res) {
      that.priceInfo = res;
    },
    fail(res) {
      console.log("fail");
      alert("接口报错");
    },
  });
}
</script>

<style scoped>
h2 {
  font-size: 30px;
  margin-left: 310px;
  color: white;
  letter-spacing: 3px;
}

.hidden {
  display: none;
}

#bg {
  /*border-radius: 10px;*/
  /*border: 1px solid #979797;*/
  background: #ffffff;
  overflow-x: hidden;
}

.btn4 {
  width: 149px;
  float: right;
  height: 40px;
  background: #4a90e2;
  border: none;
  border-radius: 3px;
  color: white;
  position: relative;
  right: 0;
  font-size: 14px;
  margin-top: 8px;
  margin-right: 63px;
}

.btn4:hover {
  cursor: pointer;
}

.top {
  height: 55px;
  background: #4381e6;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
  padding-top: 25px;
}

::-webkit-scrollbar {
  width: 2px;
}

.title {
  font-size: 20px;
  font-weight: bolder;
  display: block;
}

.container {
  width: 600px;
  margin: 25px auto;
}

.d1 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 15px;
  font-size: 14px;
  margin-left: 10px;
}

.d2 {
  width: 330px;
  text-align: center;
}

.tips {
  background: #ffffff;
  border: 1px solid #cccccc;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  position: fixed;
  top: 0;
  left: 40%;
  width: auto;
  height: 65px;
  z-index: 99;
}

.tips img {
  width: 30px;
  height: 30px;
  position: relative;
  margin-top: 18px;
  margin-left: 66px;
}

.tips span {
  font-size: 15px;
  color: #3c3c3c;
  letter-spacing: -0.05px;
  line-height: 16px;
  display: inline-block;
  position: relative;
  top: -8px;
  margin-left: 13px;
  padding-right: 66px;
}

input:-ms-input-placeholder {
  font-size: 12px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}

.top-icon:hover {
  cursor: pointer;
}

.bottom-icon:hover {
  cursor: pointer;
}
</style>
